package main

import (
	"context"
	"flag"
	"neo4j-go-try/internal/conf"
	"neo4j-go-try/internal/db"
	"os"
	"path/filepath"

	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"neo4j-go-try/internal/cases"
)

var (
	slog         *zap.SugaredLogger
	neo4jConfPtr *conf.Neo4jSection
)

func main() {
	initLog()
	readConfig()
	neo := db.NewNeo(slog, neo4jConfPtr.Uri, neo4jConfPtr.User, neo4jConfPtr.Password)
	defer neo.Close()
	dao := db.NewDAO(neo, neo4jConfPtr.Database)
	nc := cases.NewNeo4jCase(slog, dao, neo)
	ctx := context.Background()
	nc.RunCase_ListUsersWithRole(ctx)
	nc.RunCase_PagedUsersWithRole(ctx)
	// nc.RunCase_CreateAdminRole(ctx)
	// nc.RunCase_GetUser(ctx)
	// nc.RunCase_CreateUserBelongsToNormal(ctx)
	// nc.RunCase_CreateUserBelongsToAdmin(ctx)
	// nc.RunCase_FindDirectorByMovieTitle(ctx, "The Matrix")
	// nc.RunCase_FindPersonByName(ctx, "Tom Hanks")
}

func initLog() {
	c := zap.NewProductionEncoderConfig()
	c.EncodeTime = zapcore.ISO8601TimeEncoder
	c.TimeKey = "time"
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(c),
		zapcore.AddSync(os.Stdout),
		zap.NewAtomicLevelAt(zap.InfoLevel))
	logger := zap.New(core, zap.AddStacktrace(zapcore.FatalLevel), zap.AddCaller())
	defer logger.Sync()
	zap.ReplaceGlobals(logger)
	// logger.Info("initlog", zap.String("name", "hhhhhh"))
	slog = zap.S()
	slog.Infof("global SugaredLogger after %s", "neo4j-go-try")
}

func readConfig() {
	flag.String("c", "conf/config.toml", "set configuration `file`")
	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
	//解析flag
	pflag.Parse()
	//viper绑定pflag
	viper.BindPFlags(pflag.CommandLine)
	viper.SetConfigType("toml")
	configValue := viper.GetString("c")
	viper.AddConfigPath(filepath.Dir(configValue))
	viper.SetConfigName(filepath.Base(configValue))

	err := viper.ReadInConfig()
	if err != nil {
		slog.Panicf("Fatal error config file: %s \n", err)
	}

	neo4jConfPtr = conf.ReadNeo4j(viper.Sub("neo4j"), slog)
}
